<script setup>
import {ref, onMounted} from "vue";
import {Search, Tickets} from "@element-plus/icons-vue";
import {deleteAdvertise, fetchAdvertiseList, updateAdvertiseStatus} from "@/api/marketingAdvertise.js";
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from "element-plus";


const router = useRouter()
// 定义格式化日期的函数
const formatDate = (date) => {
  // 检查是否为 Date 对象
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

onMounted(() => {
  getAdvertiseList();
})

// 定义数据
const formRef = ref();
const formAdvertise = ref({
  name: null,
  type: null,
  endTime: null
});
const defaultTypeOptions = [
  {label: 'PC首页轮播', value: 0},
  {label: 'APP首页轮播', value: 1}
];
const typeOptions = {...defaultTypeOptions}

// TODO: 搜索
const handleSearch = () => {
  listQuery.name = formAdvertise.value.name;
  listQuery.type = formAdvertise.value.type;
  listQuery.endTime = formAdvertise.value.endTime;
  getAdvertiseList();
}

// TODO: 重置
const handleResetSearch = () => {
  formAdvertise.value = {
    name: null,
    type: null,
    endTime: null,
  };
  listQuery.name = null;
  listQuery.type = null;
  listQuery.endTime = null;
  getAdvertiseList();
}

// TODO: 添加
const handleAdd = () => {
  router.push({
    path: '/marketing/updateAdvertise'
  });
}

// TODO: 编辑
const handleEdit = (row) => {
  router.push({
    path: '/marketing/updateAdvertise',
    query: {id: row.id}
  });
}

// TODO: 删除
const handleDelete = (row) => {
  handleDeleteAdvertise(row.id)
}
const handleDeleteAdvertise = (ids) => {
  ElMessageBox.confirm('确认删除该广告吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let data = new URLSearchParams();
    data.append("ids", ids);
    deleteAdvertise(data).then((res) => {
      ElMessage.warning(res.data.message)
      console.log(data, '删除成功',res.data.message);
      getAdvertiseList();
    }).catch(() => {
      ElMessage.error('删除失败');
    });
  }).catch(() => {
    ElMessage.info('取消操作');
  });
}

// TODO: 更新状态
const handleUpdateStatus = (row) => {
  ElMessageBox.confirm('是否要修改上线/下线状态?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const res = updateAdvertiseStatus(row.id, {status: row.status});
    res.then((res) => {
      ElMessage.warning(res.data.message)
      ElMessage.success('修改成功');
      getAdvertiseList();
    }).catch(() => {
      ElMessage.error('修改失败');
    })
  }).catch(() => {
    ElMessage.info('取消操作');
  });
}

// TODO: 请求参数
const defaultListQuery = {
  pageNum: 1,
  pageSize: 5,
  name: null,
  type: null,
  endTime: null
};
const total = ref(0);
const listQuery = Object.assign({}, defaultListQuery);
const advertiseList = ref([]);
// TODO: 请求数据
const getAdvertiseList = async () => {
  const res = await fetchAdvertiseList(listQuery);
  advertiseList.value = res.data.data.list;
  total.value = res.data.data.total;
}

// TODO: 批量操作
const operates = [
  {value: 'delete', label: '删除'},
  {value: 'update', label: '下线'},
  {value: 'online', label: '上线'}
];
const operateType = ref('');
const handleBatchOperate = () => {
  console.log(operateType.value);
}

// TODO: 分页操作方法
const handleCurrentChange = (currentPage) => {
  listQuery.pageNum = currentPage
  getAdvertiseList()
}
const handleSizeChange = (pageSize) => {
  listQuery.pageSize = pageSize
  listQuery.pageNum = 1
  getAdvertiseList()
}

</script>

<template>
  <div class="advertise-list">
    <!--    顶部搜索区域-->
    <div class="top-bar">
      <div class="logo">
        <div class="logo-text">
          <el-icon>
            <Search/>
          </el-icon>
          <span>筛选搜索</span>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="handleSearch()">查询结果</el-button>
          <el-button icon="refresh" @click="handleResetSearch()">重置</el-button>
        </div>
      </div>
      <div class="search">
        <el-form ref="formRef" :inline="true" v-model="formAdvertise" label-width="100px">
          <el-form-item label="广告名称:">
            <el-input v-model="formAdvertise.name" placeholder="请输入商品名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="广告位置：">
            <el-select v-model="formAdvertise.type" placeholder="请选择广告位置" clearable>
              <el-option v-for="item in typeOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="到期时间：">
            <el-date-picker
                v-model="formAdvertise.endTime"
                type="date"
                placeholder="选择到期时间"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!--   中部添加按钮 -->
    <div class="center-bar">
      <div class="add-btn">
        <el-icon>
          <Tickets/>
        </el-icon>
        <span>数据列表</span>
      </div>
      <el-button type="primary" icon="plus" @click="handleAdd(null)" style="margin-left: 20px;">
        添加广告
      </el-button>
    </div>

    <!--    底部商品列表 -->
    <div class="bottom-bar">
      <el-table :data="advertiseList" border style="width: 100%;">
        <el-table-column type="selection" width="80" align="center"></el-table-column>
        <el-table-column label="广告ID" align="center">
          <template #default="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="广告名称" width="200" align="center">
          <template #default="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="广告图片" width="350" align="center">
          <template #default="{row}">
            <img :src="row.pic" alt="" style="width: 200px;height: 100px;margin: 10px;">
          </template>
        </el-table-column>
        <el-table-column label="广告位置" align="center">
          <template #default="{row}">
            <span>{{ row.type === 1 ? 'App首页轮播' : 'PC首页轮播' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="播放时间" align="center">
          <template #default="{row}">
            <p>开始时间：{{ formatDate(row.startTime) }}</p>
            <p>到期时间：{{ formatDate(row.endTime) }}</p>
          </template>
        </el-table-column>
        <el-table-column label="上线/下线" align="center">
          <template #default="{row}">
            <el-switch
                v-model="row.status"
                @change="handleUpdateStatus(row)"
                :active-value="1"
                :inactive-value="0">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="点击次数" align="center">
          <template #default="{row}">
            <span>{{ row.clickCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="生成订单" align="center">
          <template #default="{row}">
            {{ row.orderCount }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400" align="center">
          <template #default="{row}">
            <el-button icon="edit" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button icon="delete" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="pagination">
      <div class="select-type">
        <span>批量操作：</span>
        <el-select v-model="operateType" placeholder="请选择操作">
          <el-option
              v-for="item in operates"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        <el-button
            style="margin-left: 20px"
            @click="handleBatchOperate()"
            type="primary"
            size="small">
          确定
        </el-button>
      </div>
      <el-pagination
          background
          layout="total, sizes,prev, pager, next,jumper"
          :total="total"
          :page-sizes="[5,10,15,20,25]"
          v-model:page-size="listQuery.pageSize"
          v-model:current-page="listQuery.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.advertise-list {
  height: 100%;
  display: flex;
  flex-direction: column;

  .top-bar {
    //height: 100px;
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;

    .logo {
      width: 100%;
      font-size: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        margin: 0 8px;
      }

      .search-btn {
        padding: 0 10px;
      }
    }

    .search {
      width: 100%;

      .el-form {
        margin-top: 20px;

        .el-form-item {
          width: 280px;
        }
      }
    }
  }

  .center-bar {
    //height: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;

    .add-btn {
      display: flex;
      align-items: center;

      span {
        margin-left: 8px;
        font-size: 18px;
      }
    }
  }

  .pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;
    padding: 10px 20px;

    .select-type {
      width: 400px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    span {
      width: 150px;
    }
  }
}

</style>